﻿using LuDragon.Common.Attributes;
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;

namespace LuDragon.Common.Enums
{   
    public static class EnumExtension
    {

        /// <summary>
        /// 返回Enum包含的Description特性
        /// </summary>
        /// <param name="Value"></param>
        /// <returns></returns>
        public static string GetDisplayDescription(this System.Enum Value)
        {
            object[] _attributes = Value.GetType().GetMember(Value.ToString()).First().GetCustomAttributes(true);
            return _attributes != null && _attributes.Length > 0 && _attributes[0] is DisplayAttribute
                   ? ((DisplayAttribute)_attributes[0]).Description
                   : "";
        }

        /// <summary>
        /// 获取枚举的Key信息
        /// </summary>
        /// <param name="val">枚举值</param>
        /// <returns></returns>
        public static object GetKey(this Enum val)
        {
            var type = val.GetType();
            var fd = type.GetField(val.ToString());
            if (fd == null)
                return 0;
            var attrs = fd.GetCustomAttributes(typeof(KeyValueAttribute), false);
            object key = null;
            foreach (KeyValueAttribute attr in attrs)
            {
                key = attr.Key;
            }
            return key;
        }

        /// <summary>
        /// 获取枚举的value信息
        /// </summary>
        /// <param name="val">枚举值</param>
        /// <returns></returns>
        public static string GetValue(this Enum val)
        {
            var type = val.GetType();
            var fd = type.GetField(val.ToString());
            if (fd == null)
                return string.Empty;
            var attrs = fd.GetCustomAttributes(typeof(KeyValueAttribute), false);
            var value = string.Empty;
            foreach (KeyValueAttribute attr in attrs)
            {
                value = attr.Value;
            }
            return value;
        }
    }
}